﻿
String.prototype.trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
}
String.prototype.lens = function () {
    return this.replace(/[^\x00-\xff]/g, "** ").length;
}
String.prototype.toDate = function () {
    //alert(this instanceof Date);
    var datemilliseconds;
    if (isNaN(this)) datemilliseconds = this.replace(/\D/igm, '');//使用正则表达式将日期属性中地非数字（\D）删除
    else datemilliseconds = this;

    return new Date(parseInt(datemilliseconds, 10));
}
Number.prototype.toStr = function (suffixWhenNot0, strWhen0) {
    return this == 0 ? strWhen0 ? strWhen0 : "" : suffixWhenNot0 ? this + suffixWhenNot0 : this;
};
// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
// 例子： 
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
// (new Date()).Format("yyyy-M-d h:m:s.S")	  ==> 2006-7-2 8:9:4.18 
Date.prototype.format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
var isArray = function (obj) { return Object.prototype.toString.call(obj) === '[object Array]'; }

var $utl = {
    //处理json中null
    toStr: function (val, suffixWhenNotNull, strWhenNull) {
        return !val ? strWhenNull ? strWhenNull : "" : suffixWhenNotNull ? val + suffixWhenNotNull : val;
    },
    isEmpty: function (val) {
        return val == undefined || val == null || val.length == 0;
    },
    stopBubble: function (e) {
            if (e && e.stopPropagation) {//非IE浏览器 
                e.stopPropagation();
            }
            else {//IE浏览器 
                window.event.cancelBubble = true;
            }
    },
    isArray: function (obj) { return Object.prototype.toString.call(obj) === '[object Array]'; },
    //写cookies expries以分为单位
    setCookie: function (name, value, expires) {
        var arg = arguments.length;
        if (arg == 2)
            document.cookie = name + "=" + escape(value);
        else {
            var exp = new Date();
            exp.setTime(exp.getTime() + 1000 * 60 * expires);
            document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
        }
    },
    //读取cookies
    getCookie: function (name) {
        var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
        if (arr = document.cookie.match(reg)) return unescape(arr[2]);
        else return null;
    },
    //删除cookies  
    delCookie: function (name) {
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval = getCookie(name);
        if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
    },
    // This optional function html-encodes messages for display in the page.
    htmlEncode: function (value) {
        var encodedValue = $('<div />').text(value).html();
        return encodedValue;
    },    
    //获取url参数
    request: function (paras) {

        var url = location.href;

        var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");

        var paraObj = {}

        for (i = 0; j = paraString[i]; i++) {

            paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=") + 1, j.length);

        }

        var returnValue = paraObj[paras.toLowerCase()];

        if (typeof (returnValue) == "undefined") {

            return null;

        } else {

            return returnValue;

        }
    },
    /*
    四舍五入保留小数位数
    numberRound 被处理的数
    roundDigit  保留几位小数位
    */
    roundFun: function (numberRound, roundDigit) {
        if (numberRound >= 0) {
            var tempNumber = parseInt((numberRound * Math.pow(10, roundDigit) + 0.5)) / Math.pow(10, roundDigit);
            return tempNumber;
        } else {
            numberRound1 = -numberRound
            var tempNumber = parseInt((numberRound1 * Math.pow(10, roundDigit) + 0.5)) / Math.pow(10, roundDigit);
            return -tempNumber;
        }
    },
    /*附件大小格式处理*/
    renderSize: function (value) {
        if (null == value || value == '') {
            return "0 Bytes";
        }
        var unitArr = new Array("Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB");
        var index = 0;


        var srcsize = parseFloat(value);
        var size = this.roundFun(srcsize / Math.pow(1024, (index = Math.floor(Math.log(srcsize) / Math.log(1024)))), 2);
        return size + unitArr[index];
    },
    loadImg: function (fileInfo, callback) {
        var img = new Image();
        img.src = fileInfo.url;
        if (img.complete) {
            callback(img,fileInfo);
        } else {
            img.onload = function () {
                callback(img,fileInfo);
                img.onload = null;
            }
        }
    },
    //尺寸缩放,并调整位置(position:absolute)
    //fix_h 缩放后高度固定
    presizeImg: function (img, w, h) {
        var nw = img.width,
            nh = img.height; //alert([nw, nh]);
        if ((nw > w) && w > 0) {
            nw = w;
            nh = (w / img.width) * img.height;
        }
        if ((nh > h) && h > 0) {
            nh = h;
            nw = (h / img.height) * img.width;
        }        

        img.width = nw; img.height = nh;
        img.style.left = Math.round((w - nw) / 2)+'px';
        img.style.top = Math.round((h - nh) / 2) + 'px';
        img.style.display = "";
    },
    presizeImgByUrl: function (callback, data) {
        //data{url: , w: , h: fix_h:false , p1: ...}
        var img = new Image();
        img.onload = function () {
            //alert(['load',img.width, img.height]);
            $utl.presizeImg(img, data.w, data.h);
            callback(img, data);
            img.onload = null;
        }
        img.src = data.url;
        
        //此写法ie11部分图片无法显示
        //if (img.complete) {
        //    //alert(['compalted',img.width, img.height]);
        //    this.presizeImg(img, data.w, data.h);
        //    callback(img, data);
        //} else {
        //    img.onload = function () {
        //        //alert(['load',img.width, img.height]);
        //        $utl.presizeImg(img, data.w, data.h);
        //        callback(img, data);
        //        img.onload = null;
        //    }
        //}        
    },
    clacImgZoomParam: function (width, height, maxWidth, maxHeight) {
        var param = { top: 0, left: 0, width: width, height: height };
        if (width > maxWidth || height > maxHeight) {
            rateWidth = width / maxWidth;
            rateHeight = height / maxHeight;

            if (rateWidth > rateHeight) {
                param.width = maxWidth;
                param.height = Math.round(height / rateWidth);
            } else {
                param.width = Math.round(width / rateHeight);
                param.height = maxHeight;
            }
        }

        param.left = Math.round((maxWidth - param.width) / 2);
        param.top = Math.round((maxHeight - param.height) / 2);
        return param;
    },
    //加载声音，返回声音对象
    loadAudio: function (options) {
        var defaults = {
            id: "",
            mp3: null,
            ogg: null
        };
        var ps = $.extend(defaults, options || {});
            //audioHtml = "";
        //audioHtml = '<audio id="' + ps.id + '" controls="controls" preload="auto" style="position:absolute; visibility:hidden;">' +
		//			        '<source src="' + ps.mp3 + '"></source>' +
		//			        //'<source src="' + ps.ogg + '"></source>' +
		//		        '</audio>';
        //$('<audio/>').attr('id',ps.id)
        //var audio = document.createElement("audio");
        //audio.src = ps.mp3;
        //audio.addEventListener("canplaythrough", function () {
        //    //alert('The file is loaded and ready to play!');
        //}, false);
        var a = document.createElement("audio");
        a.setAttribute("id", ps.id);
        a.setAttribute("preload", "auto");
        //ps.playcount && a.setAttribute("playcount", 2);
        
        ps.mp3 && $("<source>").attr("src", ps.mp3).appendTo(a);
        ps.ogg && $("<source>").attr("src", ps.ogg).appendTo(a);
        //a.addEventListener("canplaythrough", function () {
        //    //alert('The file is loaded and ready to play!');
        //}, false);
        a.playIf = function (loop) { loop && (a.loop = 1); a.play && a.play(); };
        document.body.appendChild(a);
        //$("body").append(audioHtml);
        return a;
    },
    //延迟加载id;js名称，防止重复加载
    lazyScript: function (url, id, callback) {       
        var m = this;
        if (window.addEventListener)
            window.addEventListener("load", function () { m.downloadScript(url, id, callback); }, false);
        else if (window.attachEvent)
            window.attachEvent("onload", function () { m.downloadScript(url, id, callback); });
        else window.onload = function () { m.downloadScript(url, id, callback); };
    },
    downloadScript: function (url, id, callback) {
        var script = document.getElementById(id);
        //已创建
        if (script && callback) {
            //防止script还没加载好,一定时间检查一次，直到加载好执行回调
            (function callbackWhenLoaded(call) {
                setTimeout(function () {
                    if (script.getAttribute('loaded')) {
                        //console.log('oh loaded...');
                        callback();
                    } else {
                        //console.log('try when loaded...');
                        callbackWhenLoaded(call);
                    }
                }, 100);
            })(callback);            
            return;
        } else if (script) { return;}
        
        script = document.createElement('script');
        script.type = 'text/javascript';
        script.charset = 'utf-8';
        script.src = url;
        script.id = id;
        
        document.getElementsByTagName('head')[0].appendChild(script);
        if (typeof callback == 'function')
            script.onload = script.onreadystatechange = function () {
                if (script.readyState && script.readyState != 'loaded' && script.readyState != 'complete')
                    return;
                script.setAttribute('loaded', 'loaded');
                script.onreadystatechange = script.onload = null;
                callback();
            }

        
    },
    //产生固定位数随机数据
    genRandom: function (len) {
        var n = "";
        for (var i = 0; i < len; i++) {
            n += Math.floor(Math.random() * 10);
        }
        return n;
    },//signalr不支持的浏览器
    unsupportBrowser: function () {
        var win = window;
        var isIe = win.ActiveXObject || win.document.documentMode;
        if (isIe || typeof win.scrollMaxX !== 'undefined' || /^Apple/.test(win.navigator.vendor || '')) {
            return false;
        }
        var _track = 'track' in document.createElement('track');
        var webstoreKeysLength = win.chrome && win.chrome.webstore ? Object.keys(win.chrome.webstore).length : 0;
        if (_track) {
            // 360极速 360安全
            return webstoreKeysLength > 1 ? false : true;//360安全浏览器
        }
        return false;
    }
}